package com.lanhai.crowd.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lanhai.crowd.constant.CrowdConstant;
import com.lanhai.crowd.entity.Admin;
import com.lanhai.crowd.entity.AdminExample;
import com.lanhai.crowd.exception.LoginAcctAlreadyInUseException;
import com.lanhai.crowd.exception.LoginAcctAlreadyInUseForUpdateException;
import com.lanhai.crowd.exception.LoginFailedException;
import com.lanhai.crowd.mapper.AdminMapper;
import com.lanhai.crowd.service.api.AdminService;
import com.lanhai.crowd.util.CrowdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    Logger log = LoggerFactory.getLogger(AdminServiceImpl.class);

    /**
     * [测试]注册用户方法
     *
     * @param admin
     */
    @Override
    public void saveAdmin(Admin admin) {

        try {
            adminMapper.insert(admin);
        } catch (Exception e) {
            e.printStackTrace();

            log.info("抛出异常类的信息：" + e.getClass().getName());

            // 新增用户名重复抛出该异常
            if(e instanceof DuplicateKeyException) {
                throw new LoginAcctAlreadyInUseException(CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE);
            }
        }

    }

    /**
     * [测试]获取全部用户的方法
     *
     * @return
     */
    @Override
    public List<Admin> getAll() {
        return adminMapper.selectByExample(new AdminExample());
    }

    /**
     * 登录检查
     *
     * @param user 用户名
     * @param pwd  密码
     * @return 如果可以登陆返回admin对象, 否则返回null
     */
    @Override
    public Admin getLoginAdmin(String user, String pwd) {

        // 1.检查用户名合法性
        if (CrowdUtil.isEmpty(user))
            // 如果为空抛出登录异常
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);

        // 2.检查密码合法性
        // 2.1获取md5
        String encoded = CrowdUtil.md5(pwd);

        // 2.2检查密码是否为空
        if (CrowdUtil.isEmpty(encoded))
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);

        // 3通过用户名和密码检查数据库是否存在该用户
        AdminExample adminExample = new AdminExample();

        // 3.1创建Criteria对象
        AdminExample.Criteria criteria = adminExample.createCriteria();

        // 3.2在Criteria对象中封装查询条件
        criteria.andLoginAcctEqualTo(user);
        List<Admin> adminList = adminMapper.selectByExample(adminExample);

        // 3.3检查adminList是否为空
        if (null == adminList || adminList.size() == 0)
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);

        // 3.4如果为多个，抛出系统异常
        if (adminList.size() > 1)
            throw new RuntimeException(CrowdConstant.MESSAGE_LGOIN_SYSTEM_ACCT_NOT_UNIQUE);

        // 3.5从adminList中取出用户
        int index = 0;
        Admin admin = adminList.get(index);
        // 3.6比较密码是否正确
        if (!Objects.equals(encoded, admin.getUserPwd()))
            // 不正确抛出登录异常
            throw new LoginFailedException(CrowdConstant.MESSAGE_LOGIN_FAILED);

        // 4登录正确返回admin对象
        return admin;
    }

    /**
     * 根据关键词进行分页查询
     *
     * @param keyword  关键词
     * @param pageNum  开始页码
     * @param pageSize 页码数
     * @return PageInfo对象
     */
    @Override
    public PageInfo<Admin> getPageInfo(String keyword, Integer pageNum, Integer pageSize) {

        // 1.调用PageHelper的静态方法开启分页查询
        // 这里体现了pagehelper的‘非侵入式’设计
        PageHelper.startPage(pageNum, pageSize);

        // 2.执行查询
        List<Admin> list = adminMapper.selectAdminByKeyword(keyword);

        // 3.封装到PageInfo对象中
        return new PageInfo<>(list);
    }

    @Override
    public void remove(Integer adminId) {
        adminMapper.deleteByPrimaryKey(adminId);
    }


    @Override
    public Admin getAdminById(Integer adminId) {
        return adminMapper.selectByPrimaryKey(adminId);
    }

    @Override
    public void updateAdmin(Admin admin) {
        try {
            // 有选择的更新字段  null值字段不更新
            adminMapper.updateByPrimaryKeySelective(admin);
        } catch (Exception e) {
            e.printStackTrace();

            if (e instanceof DuplicateKeyException) {
                // 如果修改出现重复用户名，则抛出该异常
                throw new LoginAcctAlreadyInUseForUpdateException(
                        CrowdConstant.MESSAGE_LOGIN_ACCT_ALREADY_IN_USE
                );
            }
        }


    }


}
